package com.example.maybeaccount;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Mode.Account;
import com.example.maybeaccount.Mode.AlarmService;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.SqliteDB;

/** 查看账单详情活动 */
public class ActivityShowDetails extends AppCompatActivity {
    private int firstFlag = 0;
    private boolean isTop;
    private int mode;
    private Item item;
    private Button buttonEdit;
    private Button buttonDelete;
    private Button buttonPayBack;
    private Button buttonBack;
    private Button buttonAmount ;
    private TextView textClass1;
    private TextView textClass2;
    private TextView textSetUpTime;
    private TextView textPayBackTime;
    private TextView textMember;
    private TextView textShop;
    private TextView textProject;
    private TextView textRemark;
    private TextView textAccount;
    private Button buttonPayBackConf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        if(savedInstanceState != null){
            mode = savedInstanceState.getInt("mode",4);
            item = (Item) savedInstanceState.getSerializable("item");
            mode = item.getMode();
        }else{
            Intent intent = getIntent();
            mode = intent.getIntExtra("mode",4);
            item = (Item) intent.getSerializableExtra("item");
            mode = item.getMode();
        }

        initShow();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putInt("mode",mode);
        outState.putSerializable("item",item);
    }

    /** 后台唤醒处理 */
    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(ActivityShowDetails.this, Entrance.class);
            intent.putExtra("resume","ShowDetails");
            intent.putExtra("item",item);
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }
    @Override
    protected void onPause(){
        super.onPause();
        isTop = false;
    }

    /**
     * 重写返回键，确保回到主界面，而不是登录
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){

            String prevActivity = getIntent().getStringExtra("activity");
            Intent intent;
            if(prevActivity.equals("MainActivity")){
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
            }else if(prevActivity.equals("ChartClass2Activity")){
                finish();
            }else{
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
            }
        }
        return true;
    }

    private void initGlobalButton(){
        buttonEdit = findViewById(R.id.button_edit);
        buttonDelete = findViewById(R.id.button_delete);
        buttonBack = findViewById(R.id.button_back);

        /** 返回键 */
        buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstFlag = 0;
                String prevActivity = getIntent().getStringExtra("activity");
                Intent intent;
                if(prevActivity.equals("MainActivity")){
                    intent = new Intent(ActivityShowDetails.this, MainActivity.class);
                    startActivity(intent);
                }else if(prevActivity.equals("ChartClass2Activity")){
                    finish();
                }else{
                    finish();
                }
            }
        });

        /** 编辑键 */
        buttonEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        /** 删除键 */
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder  = new AlertDialog.Builder(ActivityShowDetails.this);
                builder.setTitle("删除账单" ) ;
                builder.setMessage("确认要删除账单？" ) ;
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /** 删除当前账单 */
                        Account account = SqliteDB.getInstance(getApplicationContext()).getAccountOfName(item.getAccount());
                        account.updateData((-1)*item.getAmount());
                        SqliteDB.getInstance(getApplicationContext()).updateAccount(account);
                        int result = SqliteDB.getInstance(getApplicationContext()).deleteItem(item.getId());
                        if(result == 1){
                            Toast.makeText(ActivityShowDetails.this,"删除成功",Toast.LENGTH_LONG).show();
                            Intent intent= new Intent(ActivityShowDetails.this, MainActivity.class);
                            startActivity(intent);
                        }else{
                            Toast.makeText(ActivityShowDetails.this,"删除失败",Toast.LENGTH_LONG).show();
                        }
                    }
                });
                builder.setNegativeButton("再想想", null);
                builder.show();
            }
        });

        if(mode == Item.MODE_CREDIT){
            buttonPayBack = findViewById(R.id.payback_check);
            buttonPayBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Account account;
                    /** 更新当前账单 */
                    item.setMode(Item.MODE_CREDIT_PAYBACK);
                    SqliteDB.getInstance(getApplicationContext()).updateItem(item);
                    /** 创建新的支出账单 */
                    item.setMode(Item.MODE_OUTCOME);
                    SqliteDB.getInstance(getApplicationContext()).saveItem(item);
                    if(item.getAccount().equals( "蚂蚁花呗")){
                        account = SqliteDB.getInstance(getApplicationContext()).getAccountOfName("支付宝");
                        item.setAccount("支付宝");
                    }else if(item.getAccount().equals("京东白条")){
                        account = SqliteDB.getInstance(getApplicationContext()).getAccountOfName("微信支付");
                        item.setAccount("微信");
                    }else{
                        account = SqliteDB.getInstance(getApplicationContext()).getAccountOfName("支付宝");
                    }
                    account.updateData((-1)*Math.abs(item.getAmount()));
                    if(SqliteDB.getInstance(getApplicationContext()).updateAccount(account) == 1){
                        //Toast.makeText(ActivityShowDetails.this,"",Toast.LENGTH_LONG).show();
                        buttonPayBack.setText("您已还款");
                    }
                }
            });
        }else if(mode == Item.MODE_CREDIT_PAYBACK){
            buttonPayBack = findViewById(R.id.payback_check);
            buttonPayBack.setText("您已还款");
        }

    }

    private void initShow(){
        switch (mode){
            /** 展示收入 */
            case Item.MODE_INCOME:
                setContentView(R.layout.fragment_income_show);
                initGlobalButton();
                initIncomeView();
                break;
            /** 展示支出 */
            case Item.MODE_OUTCOME:
                setContentView(R.layout.fragment_outcome_show);
                initGlobalButton();
                initExpendView();
                break;
            /** 展示信贷 */
            case Item.MODE_CREDIT:
                setContentView(R.layout.fragment_credit_show);
                initGlobalButton();
                initCreditView();
                break;
            case Item.MODE_CREDIT_PAYBACK:
                setContentView(R.layout.fragment_credit_show);
                initGlobalButton();
                initCreditView();
                break;
            default:
        }
    }

    private void initIncomeView(){
        buttonAmount = findViewById(R.id.choose_amount);
        textClass1 = findViewById(R.id.class1);
        textAccount = findViewById(R.id.account);
        textSetUpTime = findViewById(R.id.input_time);
        textRemark = findViewById(R.id.remark);

        buttonAmount.setText(item.getAmount()+"");
        textClass1.setText(item.getClass1());
        textAccount.setText(item.getAccount());
        textSetUpTime.setText(item.getStringTime());
        textRemark.setText(item.getRemark());

    }
    private void initExpendView(){
        buttonAmount = findViewById(R.id.choose_amount);
        textClass1 = findViewById(R.id.class1);
        textClass2 = findViewById(R.id.class2);
        textAccount = findViewById(R.id.account);
        textSetUpTime = findViewById(R.id.input_time);
        textMember = findViewById(R.id.member);
        textShop = findViewById(R.id.shop);
        textProject = findViewById(R.id.project);
        textRemark = findViewById(R.id.remark);

        buttonAmount.setText(Math.abs(item.getAmount())+"");
        textClass1.setText(item.getClass1());
        textClass2.setText(item.getClass2());
        textAccount.setText(item.getAccount());
        textSetUpTime.setText(item.getStringTime());
        textMember.setText(item.getMember());
        textShop.setText(item.getShop());
        textProject.setText(item.getProject());
        textRemark.setText(item.getRemark());

    }

    private void initCreditView(){
        buttonAmount = findViewById(R.id.choose_amount);
        textClass1 = findViewById(R.id.class1);
        textClass2 = findViewById(R.id.class2);
        textAccount = findViewById(R.id.platform);
        textSetUpTime = findViewById(R.id.input_time2);
        textPayBackTime = findViewById(R.id.input_repaytime);
        textMember = findViewById(R.id.member);
        textShop = findViewById(R.id.shop);
        textProject = findViewById(R.id.project);
        textRemark = findViewById(R.id.remark);
        //buttonPayBack = findViewById(R.id.payback_check);

        buttonAmount.setText(Math.abs(item.getAmount())+"");
        textClass1.setText(item.getClass1());
        textClass2.setText(item.getClass2());
        textAccount.setText(item.getAccount());
        textSetUpTime.setText(item.getStringTime());
        textPayBackTime.setText(item.getStringPayBackTime());
        textMember.setText(item.getMember());
        textShop.setText(item.getShop());
        textProject.setText(item.getProject());
        textRemark.setText(item.getRemark());

    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }
}
